from django.db import models
from django.db.models.signals import pre_save
from django.conf import settings

FLICKR_LICENSES = (
    ('0', 'All Rights Reserved'),
    ('1', 'Attribution-NonCommercial-ShareAlike License'),
    ('2', 'Attribution-NonCommercial License'),
    ('3', 'Attribution-NonCommercial-NoDerivs License'),
    ('4', 'Attribution License'),
    ('5', 'Attribution-ShareAlike License'),
    ('6', 'Attribution-NoDerivs License'),
)

class Owner(models.Model):
    nsid = models.CharField(max_length=50, unique=True)
    username = models.CharField(blank=True, max_length=100)
    realname = models.CharField(blank=True, max_length=100)
    location = models.CharField(blank=True, max_length=100)
    photos_url = models.URLField(blank=True, verify_exists=False)
    profile_url = models.URLField(blank=True, verify_exists=False)
    iconserver = models.PositiveIntegerField(default=0)
    iconfarm = models.PositiveIntegerField(default=0)
    
    def __unicode__(self):
        if self.realname:
            return self.realname
        
        if self.username:
            return self.username
        
        return self.nsid
    
    def _get_details(self, api):
        o = api.people_getInfo(user_id=self.nsid).find('person')
        
        self.username = o.find('username').text
        self.photos_url = o.find('photosurl').text
        self.profile_url = o.find('profileurl').text
        self.realname = o.find('realname').text or ''
        self.location = o.find('location').text or ''
        self.iconserver = o.attrib['iconserver']
        self.iconfarm = o.attrib['iconfarm']
    
    def save(self, get_details=True, api=None, **options):
        
        if get_details:
            if api is None:
                from utils import flickrapi
                api = flickrapi()
            self._get_details(api)
        
        super(Owner, self).save(**options)

class Note(models.Model):
    flickr_id = models.PositiveIntegerField(unique=True)
    author = models.ForeignKey(Owner)
    x = models.PositiveIntegerField()
    y = models.PositiveIntegerField()
    w = models.PositiveIntegerField()
    h = models.PositiveIntegerField()
    text = models.TextField(blank=True)

class Photo(models.Model):
    flickr_id = models.PositiveIntegerField(unique=True)
    secret = models.CharField(max_length=100)
    owner = models.ForeignKey(Owner)
    server = models.PositiveIntegerField()
    farm = models.PositiveIntegerField()
    title = models.CharField(max_length=200)
    is_public = models.BooleanField(default=True)
    is_friend = models.BooleanField(default=False)
    is_family = models.BooleanField(default=False)
    allow_comments = models.PositiveSmallIntegerField(default=0)
    allow_meta = models.PositiveSmallIntegerField(default=0)
    license = models.CharField(max_length=50, choices=FLICKR_LICENSES)
    description = models.TextField(blank=True)
    date_taken = models.DateTimeField(blank=True)
    date_posted = models.DateTimeField(blank=True)
    date_update = models.DateTimeField(blank=True)
    comment_count = models.PositiveIntegerField(default=0)
    photopage_url = models.URLField(blank=True)
    
    height = models.PositiveSmallIntegerField(default=0)
    width = models.PositiveSmallIntegerField(default=0)
    
    geo_location = models.CharField(max_length=150, blank=True)
    geo_latitude = models.FloatField(default=0)
    geo_longitude = models.FloatField(default=0)
    geo_accuracy = models.PositiveIntegerField(default=0)
    
    def __unicode__(self):
        return self.title
    
    next = None
    prev = None
    
    def get_prev(self):
        if self.prev:
            return self.prev
        ret = False
        for p in Photo.objects.filter(date_posted__lte=self.date_posted):
            if ret:
                self.prev = p
                return p
            
            if p.id == self.id:
                ret = True
    
    def get_next(self):
        if self.next:
            return self.next
        
        prev = False
        for p in Photo.objects.filter(date_posted__gte=self.date_posted):
            if p.id == self.id:
                self.next = prev
                return prev
            
            prev = p
    
    def _get_url(self, size=False):
        args = [
            self.farm,
            self.server,
            self.flickr_id,
            self.secret,
        ]
        
        if size in ('s', 't', 'm', 'b'):
            args.append(size)
            return 'http://farm%d.static.flickr.com/%d/%d_%s_%s.jpg' % tuple(args)
        else:
            return 'http://farm%d.static.flickr.com/%d/%d_%s.jpg' % tuple(args)
    
    @property
    def square_url(self):
        return self._get_url('s')
    
    @property
    def thumbnail_url(self):
        return self._get_url('t')
    
    @property
    def small_url(self):
        return self._get_url('m')
    
    @property
    def medium_url(self):
        return self._get_url('-')
    
    @property
    def large_url(self):
        return self._get_url('b')
    
    @models.permalink
    def get_absolute_url(self):
        return ('flickr.photo', (), {'photo_id': self.id})
    
    def _get_details(self, api):
        # This way we have italian location names
        api.add_header('Cookie', 'cookie_l10n=it-it%3Bus')
        p = api.photos_getInfo(photo_id=self.flickr_id, secret=self.secret).find('photo')
        
        self.description = p.find('description').text or ''
        comment_count = int(p.find('comments').text)
        self.license = p.attrib['license']
        
        # dates
        from datetime import date
        
        dates = p.find('dates')
        self.date_taken = dates.attrib['taken']
        self.date_posted = date.fromtimestamp(float(dates.attrib['posted']))
        self.date_update = date.fromtimestamp(float(dates.attrib['lastupdate']))
        
        # url
        for url in p.find('urls').getiterator('url'):
            if url.attrib['type'] == 'photopage':
                self.photopage_url = url.text
        
        # permissions
        perms = p.find('permissions')
        if perms:
            self.allow_comments = perms.attrib['permcomment']
            self.allow_meta = perms.attrib['permaddmeta']
        
        # location
        location = p.find('location')
        if location:
            self.geo_latitude = location.attrib['latitude']
            self.geo_longitude = location.attrib['longitude']
            self.geo_accuracy = location.attrib['accuracy']
            
            locations = []
            for names in location.getiterator():
                if len(names.text.strip()):
                    locations.append(names.text.strip())
            self.geo_location = ", ".join(locations)
        
        # sizes
        from xml.etree.ElementTree import tostring
        
        s = api.photos_getSizes(photo_id=self.flickr_id).find('sizes')
        for size in s.getiterator('size'):
            if size.attrib['label'] == u'Medium':
                self.width = size.attrib['width']
                self.height = size.attrib['height']
    
    def save(self, get_details=True, api=None, **options):
        
        if get_details:
            if api is None:
                from utils import flickrapi
                api = flickrapi()
            self._get_details(api)
        
        super(Photo, self).save(**options)
        
    class Meta:
        ordering = ['-date_posted', 'id']